package com.example.fast.web.interceptor;

import com.example.fast.common.annotation.Login;
import com.example.fast.common.constant.AppConstant;
import com.example.fast.common.exception.TokenException;
import com.example.fast.common.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器，对请求进行身份验证
 */
@Component
public class TokenInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        Login annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
            annotation = annotation != null ? annotation : ((HandlerMethod) handler).getBeanType().getAnnotation(Login.class);
        } else {
            return true;
        }
        if (annotation == null) {
            return true;
        }

        String postFix = "";
        if (request.getRequestURI().contains("/v1/candidate/")) {
            postFix = "-candidate";
        } else if (request.getRequestURI().contains("/v1/recruiter/")) {
            postFix = "-recruiter";
        } else if (request.getRequestURI().contains("/v1/admin/")) {
            postFix = "-admin";
        }

        //获取用户凭证
        String token = request.getHeader(jwtUtils.getHeader() + postFix);
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(jwtUtils.getHeader() + postFix);
        }

        //凭证为空
        if (StringUtils.isBlank(token)) {
            throw new TokenException("token丢失");
        }

        Claims claims = jwtUtils.getClaimByToken(token);
        if (claims == null || jwtUtils.isTokenExpired(claims.getExpiration())) {
            throw new TokenException("token失效，请重新登录");
        }

        //设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(AppConstant.USER_KEY, Long.parseLong(claims.getSubject()));

        return true;
    }
}
